package com.hillky.loadbalancer.impl;

import com.hillky.YrpcBootstrap;
import com.hillky.exceptions.LoadBalancerException;
import com.hillky.loadbalancer.AbstractLoadBalancer;
import com.hillky.loadbalancer.Selector;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 最短响应时间的负载均衡策略
 */
@Slf4j
public class MinimumResponseTimeLoadBalancer extends AbstractLoadBalancer {
    @Override
    protected Selector getSelector(List<InetSocketAddress> serviceList) {
        return new MinimumAResponseTimeSelector(serviceList);
    }

    private static class  MinimumAResponseTimeSelector implements Selector{

        private List<InetSocketAddress> serviceList;


        public MinimumAResponseTimeSelector(List<InetSocketAddress> serviceList) {
            this.serviceList = serviceList;
        }

        @Override
        public InetSocketAddress getNext() {
            Map.Entry<Long, Channel> entry = YrpcBootstrap.ANSWER_TIME_CHANNEL_CACHE.firstEntry();
            if(entry!=null){

                if(log.isDebugEnabled()){
                    log.debug("选取了响应时间为【{}】毫秒的服务节点",entry.getKey());
                }

                return (InetSocketAddress)entry.getValue().remoteAddress();
            }

            //直接从缓存中获取一个可用的就行
            Channel channel = (Channel)YrpcBootstrap.CHANNEL_CACHE.values().toArray()[0];

            return (InetSocketAddress) channel.remoteAddress();
        }

    }
}
